package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.util.DistributedLocker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/*****
 * @Author: http://www.itheima.com
 * @Description: com.itheima.controller.RedPacketController
 ****/
@RestController
@RequestMapping(value = "/red")
public class RedPacketController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private DistributedLocker distributedLocker;

    /****
     * 用户红包金额
     * @return
     */
    @GetMapping(value = "/packet/{username}")
    public String packet(@PathVariable(value = "username") String username) {
        //1)查询Redis
        String money = stringRedisTemplate.boundValueOps(username).get();

        //2)如果有数据，则直接返回
        if(!StringUtils.isEmpty(money)){
            return money;
        }

        //3)没有数据，则查询MySQL，并将结果集存储到Redis
        //查询数据库
        money = daoQueryByUserName(username);

        //if(!StringUtils.isEmpty(money)){
            //存储到Redis缓存
            stringRedisTemplate.boundValueOps(username).set(!StringUtils.isEmpty(money)? money:"0");
        //}
        return money;
    }


    /****
     * 所有用户红包金额记录排行
     */
    @GetMapping(value = "/all")
    public Object all() {
        //1）查询缓存是否存在缓存数据
        Object allMoney = stringRedisTemplate.boundValueOps("AllRedPacketList").get();

        //2）如果存在，则直接返回数据
        if(!StringUtils.isEmpty(allMoney)){
            return allMoney;
        }

        //A.获取指定Key的锁
        Boolean bo = distributedLocker.lock("LockAllRed", 10L, TimeUnit.SECONDS, 10L);
        System.out.println("2001:获取锁："+bo);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //B.获取到了锁，则再判断Redis缓存中是否有数据
        if(bo){
            //C.如果没有数据，则查询数据库
            allMoney = stringRedisTemplate.boundValueOps("AllRedPacketList").get();
            if(!StringUtils.isEmpty(allMoney)){
                return allMoney;
            }
            //3）如果不存在，则要查询数据库
            //数据库查询所有
            allMoney = daoQueryAll();


            //4）将查询到的数据存入到Redis缓存
            stringRedisTemplate.boundValueOps("AllRedPacketList").set(allMoney==null? "":JSON.toJSONString(allMoney));

            //D.释放锁
            distributedLocker.unlock("LockAllRed");
            SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println("18081释放了锁："+dateTimeFormat.format(new Date()));
        }
        return allMoney;
    }


    /***
     * 模拟数据库查询所有用户抢红包记录排行
     * @return
     */
    public Map<String, String> daoQueryAll() {
        return moneys;
    }

    /****
     * 模拟数据库查询
     */
    public String daoQueryByUserName(String username) {
        return moneys.get(username);
    }

    //用户红包记录
    private static Map<String, String> moneys = initMoney();

    //初始化
    public static Map<String, String> initMoney() {
        Map<String, String> moneyMap = new HashMap<String, String>();
        moneyMap.put("wangwu", "99");
        moneyMap.put("zhaoliu", "199");
        moneyMap.put("zhangsan", "98");
        moneyMap.put("xiaohong", "25");
        moneyMap.put("zhangfei", "13");
        moneyMap.put("zhaoyun", "33");
        moneyMap.put("liubei", "22");
        moneyMap.put("sunquan", "199");
        return moneyMap;
    }
}
